package com.lamp.customer.manager;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.lamp.customer.LampServerStarter;

/**
 * 
 * @ClassName: StatusManager
 * @Description:网关状态管理器 根据心跳命令的频率，连续三个心跳命令接收不到，做Offline状态处理 
 * @author  kangjie1209@126.com
 * @date 2017年1月16日 下午3:25:52
 *
 */
public class HeartStatusManager {
	private static Logger log = Logger.getLogger(HeartStatusManager.class);
	private String cntrKey;
	private boolean isOnline;
	public static final String STATUS_ONLINE = "Online";
	public static final String STATUS_OFFLINE = "Offline";
	private Timer timer;
	private TimerTask task;

	public HeartStatusManager(String cntrKey) {
		this.cntrKey = cntrKey;
		startTimer();
		setStatus(true);
		log.debug("创建新连接, 集中器[" + cntrKey + "]状态变更为:Online");
	}

	private void startTimer() {
		log.debug("开始启用心跳定时.....");
		timer = null;
		timer = new Timer(true);

		task = null;
		task = new TimerTask() {
			@Override
			public void run() {
				setStatus(false);
				setLoopsAndLampsOffline();
				log.debug("执行心跳定时, 集中器[" + cntrKey + "]状态变更为:Offline");
			}
		};
		//心跳保持频率
		timer.schedule(task, LampServerStarter.heartbeat);
	}

	public void setOnline() {
		timer.purge();
		timer.cancel();
		setStatus(true);
		startTimer();
	}

	protected void setStatus(boolean newStatus) {
		String status = true == newStatus?"Online":"Offline";
		log.debug("设置集中器[" + cntrKey + "]状态为:" + status);
		if (newStatus != isOnline) {
			isOnline = newStatus;
			updateStatusInDB();
		}
	}

	/**
	 * 
	 * @Title: updateStatusInDB
	 * @Description: 更新数据库设备状态
	 * @author  kangjie1209@126.com
	 * @date 2017年1月16日 下午3:33:33
	 */
	private void updateStatusInDB() {
		if (isOnline) {
			updateDB(STATUS_ONLINE);
		} else {
			updateDB(STATUS_OFFLINE);
		}
	}

	protected void updateDB(String status) {
		log.debug("set cntr[" + cntrKey + "] status is " + status);
		//SiemaDAOHandler.getInstance().updateCNTR_CNTR_STTS(status, ccad);
	}

	protected void setLoopsAndLampsOffline() {
		log.debug("set loops and lamps offline for central controller offline, cntrAddress is"+ cntrKey);
		/*SiemaDAOHandler.getInstance().setAllLoopsUnkownByCntr(ccad);
		SiemaDAOHandler.getInstance().setAllLampsOfflineByCntr(ccad);*/

	}
}
